package yxy.game.pm2.active.command.belovedhero;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RMap;
import yxy.cherry.battle.Team;
import yxy.cherry.battle.module.Position;
import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.*;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_心仪武将活动;
import yxy.game.pm2.active.module.DrawStatus;
import yxy.game.pm2.active.module.actfavoritewarlord.FavouritePackage;
import yxy.game.pm2.active.module.actfavoritewarlord.FavouriteTask;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.FormatMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.godBeast.GodBeast;
import yxy.game.pm2.module.godBeast.PickedGodBeastModule;
import yxy.game.pm2.module.niubee.NiuBeeModule;

import java.util.*;

public class ActBelovedHeroHandle {

    private String code() {
        return BattleType.BELOVEHERO.name();
    }


    /**
     * 阵容保存
     *
     * @param am
     * @param request
     * @return
     */
    public Result saveFormat(ActiveModule_心仪武将活动 am, ActiveMessage.ActBelovedHeroBattleFormatSaveRequest request) {
        //必须选的那个武将id
        String id = "";
        Map<String, actfavoritewarlordlineup> allData = DataCenter.getAllData(actfavoritewarlordlineup.class);
        //找到必须选择的那个武将
        for (actfavoritewarlordlineup value : allData.values()) {
            if (value.getIsneed() == 1) {
                id = String.valueOf(value.getId());
            }
        }

        //获取传进来的武将信息
        FormatMessage.Format formatrequest = request.getFormat();
        String fu = formatrequest.getFU() == "" ? null : formatrequest.getFU();
        String fm = formatrequest.getFM() == "" ? null : formatrequest.getFM();
        String fd = formatrequest.getFD() == "" ? null : formatrequest.getFD();
        String bu = formatrequest.getBU() == "" ? null : formatrequest.getBU();
        String bm = formatrequest.getBM() == "" ? null : formatrequest.getBM();
        String bd = formatrequest.getBD() == "" ? null : formatrequest.getBD();
        int nb = formatrequest.getNB();
        //如果没有选必选的武将则返回报错码
        if (!(id.equals(fu) || id.equals(fm) || id.equals(fd) || id.equals(bu) || id.equals(bm) || id.equals(bd))) {
            return Result.ActBelovedHeroNeedSelectMustSelectHero;
        }

        Format format = new Format();
        format.setFu(fu);
        format.setFm(fm);
        format.setFd(fd);
        format.setBu(bu);
        format.setBm(bm);
        format.setBd(bd);
        format.setNb(nb);
        am.setFormat(format);//保存队伍
        am.set();
        return Result.Success;

    }

    /**
     * 可提供的武将信息
     *
     * @param fighterModuleList
     * @return
     */
    public ArrayList<FormatMessage.HeroJson> getSelectHeroJsonArrary(HashMap<String, FighterModule> fighterModuleList) {
        ArrayList<FormatMessage.HeroJson> heroJsonArray = new ArrayList<>();
        int needSelectHeroId = 0;
        Map<String, actfavoritewarlordlineup> allData = DataCenter.getAllData(actfavoritewarlordlineup.class);
        //找到必须选择的那个武将
        for (actfavoritewarlordlineup value : allData.values()) {
            if (value.getIsneed() == 1) {
                needSelectHeroId = value.getId();
            }
        }

        for (Map.Entry<String, FighterModule> entry : fighterModuleList.entrySet()) {
            String key = entry.getKey();
            FighterModule module = entry.getValue();
            //封装heroJson
            FormatMessage.HeroJson.Builder heroJson = FormatMessage.HeroJson.newBuilder();
            heroJson.setId(Integer.parseInt(key));
            heroJson.setStar(module.getStarlv());
            heroJson.setStage(module.getStage());
            heroJson.setLevel(module.getLevel());
            heroJson.setPower(module.getTotalPower());
            heroJson.setHeroid(module.getHeroId());
            int isNeed = Integer.parseInt(key) == needSelectHeroId ? 1 : 0;
            heroJson.setIsneed(isNeed);
            heroJsonArray.add(heroJson.build());
        }

        //排序
        Collections.sort(heroJsonArray, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                FormatMessage.HeroJson builder1 = (FormatMessage.HeroJson) o1;
                FormatMessage.HeroJson builder2 = (FormatMessage.HeroJson) o2;
                return builder2.getIsneed() - builder1.getIsneed();
            }
        });

        return heroJsonArray;
    }

    /**
     * 封装阵容信息（多个武将信息以及神器信息）
     *
     * @param format
     * @return
     */
    public ArrayList<FormatMessage.HeroJson> getAllHeroJsonArrary(Format format) {
        ArrayList<FormatMessage.HeroJson> heroJsonArray = new ArrayList<>();
        if (format.getFu() != null) {
            String id = format.getFu();
            addHeroJsonArray(id, "FU", heroJsonArray);
        }
        if (format.getFm() != null) {
            String id = format.getFm();
            addHeroJsonArray(id, "FM", heroJsonArray);
        }
        if (format.getFd() != null) {
            String id = format.getFd();
            addHeroJsonArray(id, "FD", heroJsonArray);
        }
        if (format.getBu() != null) {
            String id = format.getBu();
            addHeroJsonArray(id, "BU", heroJsonArray);
        }
        if (format.getBm() != null) {
            String id = format.getBm();
            addHeroJsonArray(id, "BM", heroJsonArray);
        }
        if (format.getBd() != null) {
            String id = format.getBd();
            addHeroJsonArray(id, "BD", heroJsonArray);
        }
        return heroJsonArray;
    }

    /**
     * 如果位置上有武将，就封装武将信息
     *
     * @param id
     * @param position
     * @param heroJsonArray
     */
    public void addHeroJsonArray(String id, String position, ArrayList<FormatMessage.HeroJson> heroJsonArray) {
        FormatMessage.HeroJson.Builder heroJson = FormatMessage.HeroJson.newBuilder();
        FighterModule fighterModule = getFighterModule(Integer.parseInt(id));
        heroJson.setId(Integer.parseInt(id));
        heroJson.setHeroid(fighterModule.getHeroId());
        heroJson.setStage(fighterModule.getStage());
        heroJson.setStar(fighterModule.getStarlv());
        heroJson.setPosition(position);
        heroJsonArray.add(heroJson.build());
    }

    /**
     * 获取内存的某个武将信息
     */
    public FighterModule getFighterModule(int id) {
        RMap<String, FighterModule> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:favouriteheroprovide");
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(rMap.get(String.valueOf(id)));
        FighterModule fighterModule = JSON.parseObject(jsonObject.toString(), new TypeReference<FighterModule>() {
        });
        return fighterModule;
    }

    /**
     * 获取内存全部武将信息
     *
     * @return
     */
    public HashMap<String, FighterModule> getFighterModuleList() {
        HashMap<String, FighterModule> map = new HashMap<>();
        RMap<String, FighterModule> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:favouriteheroprovide");
        for (Map.Entry<String, FighterModule> entry : rMap.entrySet()) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(rMap.get(entry.getKey()));
            FighterModule fighterModule = JSON.parseObject(jsonObject.toString(), new TypeReference<FighterModule>() {
            });
            map.put(entry.getKey(), fighterModule);
        }
        return map;
    }

    /**
     * 上阵的队伍信息
     *
     * @param format
     * @return
     */
    public Map<Position, String> formatHeros(Format format) {
        HashMap<Position, String> map = new HashMap<>();
        if (format.getFu() != null) {
            map.put(Position.FU, format.getFu());
        }
        if (format.getFm() != null) {
            map.put(Position.FM, format.getFm());
        }
        if (format.getFd() != null) {
            map.put(Position.FD, format.getFd());
        }
        if (format.getBu() != null) {
            map.put(Position.BU, format.getBu());
        }
        if (format.getBm() != null) {
            map.put(Position.BM, format.getBm());
        }
        if (format.getBd() != null) {
            map.put(Position.BD, format.getBd());
        }
        return map;
    }


    /**
     * 玩家选择的队伍信息
     */
    public TeamModule teamPlayer(String playerCode, Format format) {
        TeamModule team = new TeamModule();

        Map<Position, String> map = formatHeros(format);

        //战力
        long totalPower = 0;

        Set<Map.Entry<Position, String>> entrySet = map.entrySet();
        // 武将
        for (Map.Entry<Position, String> entry : entrySet) {
            Position position = entry.getKey();
            String id = entry.getValue();
            FighterModule fighterModule = getFighterModule(Integer.parseInt(id));
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
        }

        // 神器
        NiuBeeModule niubee = NiuBeeModule.get(playerCode);
        WeaponModule weapon = WeaponModule.create(format.getNb(), niubee.getLevel(), niubee.getRefineLevel(), niubee.getSoulLevel(), niubee.getSkillLevel());
        team.setWeapon(weapon);

        //神兽
        PickedGodBeastModule godBeastModule = PickedGodBeastModule.get(playerCode);
        for (GodBeast godBeast : godBeastModule.getGbs().values()) {
            //选择上阵的那只
            if (godBeast.isBattle() && godBeast.getSkillLevel() > 0) {
                PokemonMoudle therion = new PokemonMoudle();
                Map<String, therionskill> allData = DataCenter.getAllData(therionskill.class);
                therionskill target = null;
                for (yxy.cherry.data.bean.therionskill therionskill : allData.values()) {
                    if (therionskill.getType() == godBeast.getType() && therionskill.getLevel() == godBeast.getSkillLevel()) {
                        target = therionskill;
                        break;
                    }
                }
                therion.setId(godBeast.getCode());
                therion.setSkillGroupId(target.getSkillid()[0]);//主动技能
                team.setPokemonMoudle(therion);
                break;
            }
        }

        // 信息
        PlayerBean playerBean = PlayerBean.get(playerCode);
        team.setName(playerBean.getName());
        team.setHead(playerBean.getHead());
        team.setLevel(playerBean.getLevel());
        team.setPower(totalPower);
        team.setPlayerCode(playerCode);
        return team;
    }


    /**
     * 怪物的队伍信息
     *
     * @param id
     * @return
     */
    public TeamModule teamMonster(int id) {
        TeamModule team = new TeamModule();

        actfavoritewarlorddata data = DataCenter.getData(id, actfavoritewarlorddata.class);
        ArrayList<FighterModule> fighterModules = getMonsterFighterModuleList(id);

        //战力
        long totalPower = 0;
        // 武将
        for (int i = 0; i < data.getWarlordid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = data.getWarlordid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
        }
        // 神器
        team.setWeapon(null);
        // 信息
        team.setName(data.getName());
        team.setHead(data.getHeadid());
        team.setPower(totalPower);

        return team;
    }

    /**
     * 心仪武将怪物信息
     *
     * @param id
     * @return
     */
    public ArrayList<FighterModule> getMonsterFighterModuleList(int id) {
        RMap<String, FighterModule> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:favouriteheromonster");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(id)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

    /**
     * 挑战
     *
     * @param playerCode
     * @param am
     * @param response
     * @param monsterId
     * @return
     */
    public Result battleResponseExecute(String playerCode, ActiveModule_心仪武将活动
            am, ActiveMessage.ActBelovedHeroBattleResponse.Builder response, int monsterId) {
        BattleHandle battleHandle = new BattleHandle();
        BattleModule battleModule = BattleModule.create(playerCode);
        battleModule.setType(BattleType.BELOVEHERO);
        battleModule.setCode(code());

        // 玩家的team
        TeamModule teamA = teamPlayer(playerCode, am.getFormat());
        battleModule.setTeamA(teamA);

        // 玩家的team
        TeamModule teamB = teamMonster(monsterId);
        battleModule.setTeamB(teamB);

        Team team_a = teamA.team(true);
        Team team_b = teamB.team(false);
        team_a.setTeam对手(team_b);
        team_b.setTeam对手(team_a);

        // 处理战斗
        battleHandle.battleExecute(battleModule, team_a, team_b, 20);
        boolean isWin = battleModule.getBattleResult().equals(BattleResult.LEFT_WIN);

        BattleMessage.BattleExecuteResponse.Builder builder = BattleMessage.BattleExecuteResponse.newBuilder();
        builder.setPlayback(battleHandle.playback(battleModule));// , team_a, team_b));

        response.setBattleResp(builder);// 录像
        response.setBattleResult(battleModule.getBattleResult().getNumber());// 战果
        //录像是否保留

        //赢了并且是第一次打的就发奖励
        if (isWin && !am.getRewardList().contains(String.valueOf(monsterId))) {
            actfavoritewarlorddata data = DataCenter.getData(monsterId, actfavoritewarlorddata.class);
            Currencies rewards = new Currencies(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum()));
            new CurrencyHandle().addCurrency(playerCode, CCReason.心仪武将活动, rewards);
            response.addAllRewards(new CurrencyHandle().packItems(rewards));
            am.getRewardList().add(String.valueOf(monsterId));
            am.setProcess(monsterId + 1);//进度
            am.set();
        }

        return Result.Success;
    }


    /**
     * 商城信息
     *
     * @param am
     * @param map
     * @param type 条件
     */
    public ArrayList<ActiveMessage.ActBelovedHeroShop> getFavouritePackage(ActiveModule_心仪武将活动 am, Map<String, actfavoritewarlordshop> map, int type) {
        ArrayList<ActiveMessage.ActBelovedHeroShop> list = new ArrayList<>();

        for (FavouritePackage fp : am.getDgifts()) {
            if (fp.getType() != type) continue;

            ActiveMessage.ActBelovedHeroShop.Builder build = ActiveMessage.ActBelovedHeroShop.newBuilder();

            actfavoritewarlordshop shopdata = map.get(String.valueOf(fp.getId()));

            build.setId(shopdata.getId());//表id
            build.setGoodsid(shopdata.getChargeid());//商品id
            build.setLimitnum(shopdata.getLimit());//限购数量
            build.setBuynum(fp.getBuyNum());//购买的数量
            Currencies curs = new Currencies(Currency.create(shopdata.getItemtype(), shopdata.getItemid(), shopdata.getItemnum())); //奖励
            Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
            build.addAllCurs(items);//商品物品
            charge charge = DataCenter.getData(fp.getGoodsid(), yxy.cherry.data.bean.charge.class);
            build.setMoney(charge.getMoney());//价格

            //是否可购买：通过判断购买次数是否>=限购次数
            int canget = fp.getBuyNum() >= fp.getNumlimit() ? DrawStatus.cannotget.getStatus() : DrawStatus.canget.getStatus();
            build.setCanget(canget);//是否可购买
            list.add(build.build());
        }

        //从低到高排序
        Collections.sort(list, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                ActiveMessage.ActBelovedHeroShop builder1 = (ActiveMessage.ActBelovedHeroShop) o1;
                ActiveMessage.ActBelovedHeroShop builder2 = (ActiveMessage.ActBelovedHeroShop) o2;
                return builder1.getMoney() - builder2.getMoney();
            }
        });

        return list;
    }

    /**
     * 获取可选的武将列表
     *
     * @return
     */
    public List<Integer> getCanSelectHeroList() {
        actfavoritewarlord heroData = DataCenter.getData(2, actfavoritewarlord.class);
        int[] heroIds = heroData.getRewardid();
        List<Integer> heroIdList = new ArrayList<>();
        for (int i = 0; i < heroIds.length; i++) {
            if (heroIds[i] == 0) continue;
            heroIdList.add(heroIds[i]);
        }
        return heroIdList;
    }

    /**
     * 发奖励
     *
     * @param am
     * @param freeTaskBean
     * @param preTaskBean
     * @param task
     * @param playerCode
     * @param data
     * @return
     */
    public ArrayList<Currency> getCurs(ActiveModule_心仪武将活动 am, Task freeTaskBean, Task preTaskBean, FavouriteTask task, String playerCode, actfavoritewarlordreward data) {
        int day = am.getDay();//天数
        ActiveMessage.ActBelovedHeroShop taskShop = getTaskShop(am);

        ArrayList<Currency> freeCrus = (ArrayList<Currency>) Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
        ArrayList<Currency> preCrus = (ArrayList<Currency>) Currency.create(data.getPrewardtype(), data.getPrewardid(), data.getPrewardnum());
        ArrayList<Currency> returnCrus = new ArrayList<>();//返回的奖励
        Boolean freeIsCanReward = false;
        Boolean preIsCanReward = false;
        if (!freeTaskBean.isReward() && day >= task.getSort()) {
            returnCrus.addAll(freeCrus);
            freeIsCanReward = true;
        }

        if (!preTaskBean.isReward() && day >= task.getSort() && taskShop.getBuynum() > 0) {
            returnCrus.addAll(preCrus);
            preIsCanReward = true;
        }

        if (freeIsCanReward) {
            freeTaskBean.setReward(true);
            freeTaskBean.set();
        }

        if (preIsCanReward) {
            preTaskBean.setReward(true);
            preTaskBean.set();
        }

        new CurrencyHandle().addCurrency(playerCode, CCReason.心仪武将活动, returnCrus);

        return returnCrus;
    }


    public ActiveMessage.ActBelovedHeroShop getTaskShop(ActiveModule_心仪武将活动 am) {
        //商品表
        Map<String, actfavoritewarlordshop> map = DataCenter.getAllData(actfavoritewarlordshop.class);

        //返回卡包商品信息
        ArrayList<ActiveMessage.ActBelovedHeroShop> list = getFavouritePackage(am, map, 2);
        ActiveMessage.ActBelovedHeroShop shop = list.get(0);
        return shop;
    }

}

